import { IconWrench } from '@douyinfe/semi-icons'
import {
  BackTop,
  Banner,
  Button,
  Dropdown,
  Table,
  Typography,
} from '@douyinfe/semi-ui'
import {
  ColumnProps,
  OnChange,
  TableProps,
} from '@douyinfe/semi-ui/lib/es/table'
import { LinkType } from '@douyinfe/semi-ui/lib/es/typography/title'
import { CSSProperties, useEffect, useState } from 'react'

interface ICEllipsisText {
  text: any
  showTooltipText?: any
  link?: LinkType
  strong?: boolean
  icon?: React.ReactNode | string
}

// 文字过长时，显示 Tooltip
export function CEllipsisText(props: ICEllipsisText) {
  return (
    <Typography.Text
      link={props.link}
      strong={props.strong}
      icon={props.icon}
      ellipsis={{
        showTooltip: {
          opts: {
            content: props.showTooltipText || props.text,
            className: 'wb-w w100',
          },
        },
      }}
    >
      {props.text}
    </Typography.Text>
  )
}

interface ICTable<T> extends TableProps {
  defaultOperateClickFun?: (text: any, record: T, index: number) => void // 点击操作列的【图标按钮】时，执行的方法
  operateDropdownItem?: (text: any, record: T, index: number) => JSX.Element
  selectedRowKeyList?: (string | number)[]
  setSelectedRowKeyList?: React.Dispatch<
    React.SetStateAction<(string | number)[]>
  >
  hiddenIndex?: boolean // 是否隐藏【序号列】
  tableStyle?: CSSProperties // table样式
  onChange?: OnChange<any>
  scrollY?: number
}

export default function CTable<T>(props: ICTable<T>) {
  let newColumns: ColumnProps<T>[] = [] // 处理 columns
  if (props.columns) {
    // 增加默认渲染：文字过长，则显示 Tooltip
    props.columns.forEach((item) => {
      if (!item.render) {
        item.render = (text: any, record: T, index: number) => (
          <CEllipsisText text={text}></CEllipsisText>
        )
      }
    })
    newColumns = [...props.columns]
    if (!props.hiddenIndex) {
      newColumns.unshift({
        title: '序号',
        dataIndex: 'index',
        width: 60,
        render: (text: any, record: T, index: number) => {
          return <>{index + 1}</>
        },
      })
    }
    if (props.operateDropdownItem) {
      newColumns.push({
        title: '操作',
        dataIndex: 'operate',
        render: (text: any, record: T, index: number) => {
          return (
            <Dropdown
              clickToHide
              stopPropagation
              position={'bottomRight'}
              render={
                <Dropdown.Menu>
                  {props.operateDropdownItem!(text, record, index)}
                </Dropdown.Menu>
              }
            >
              <Button
                onClick={() => {
                  props.defaultOperateClickFun
                    ? props.defaultOperateClickFun(text, record, index)
                    : undefined
                }}
                theme="borderless"
                icon={<IconWrench />}
                type="tertiary"
              ></Button>
            </Dropdown>
          )
        },
      })
    }
  }

  const [backTopElement, setBackTopElement] = useState<JSX.Element | null>(null) // 要在dom渲染完之后，再加载 <BackTop />

  useEffect(() => {
    setBackTopElement(
      <div title="返回顶部">
        <BackTop
          style={{ bottom: 85, right: 70 }}
          target={() => document.querySelector('.semi-table-body')}
        />
      </div>
    )
  }, [])

  return (
    <>
      {props.setSelectedRowKeyList && (
        <Banner
          className="m-b-10"
          type="info"
          fullMode={false}
          description={
            <div className="flex jc-sb w100">
              <div className="m-r-10 ">
                已选择{' '}
                <strong>
                  {props.selectedRowKeyList
                    ? props.selectedRowKeyList.length
                    : 0}{' '}
                </strong>
                项
              </div>
              <Typography.Text
                title="清空"
                strong
                onClick={() => props.setSelectedRowKeyList!([])}
                link
              >
                清空
              </Typography.Text>
            </div>
          }
          closeIcon={null}
        />
      )}
      <Table
        style={props.tableStyle}
        virtualized
        scroll={{
          y: props.dataSource?.length
            ? props.scrollY
              ? props.scrollY * (document.body.clientHeight / 937)
              : (props.setSelectedRowKeyList ? 600 : 600 + 44) *
                (document.body.clientHeight / 937)
            : 10,
        }}
        columns={newColumns}
        dataSource={props.dataSource}
        pagination={props.pagination}
        expandAllRows={props.expandAllRows}
        loading={props.loading}
        rowKey={props.rowKey || 'id'}
        rowSelection={
          props.setSelectedRowKeyList !== undefined
            ? {
                selectedRowKeys: props.selectedRowKeyList,
                onChange: (selectedRowKeyList) => {
                  props.setSelectedRowKeyList!(selectedRowKeyList || [])
                },
              }
            : undefined
        }
        onChange={props.onChange}
      />

      {backTopElement}
    </>
  )
}
